#include "SDL/SDL.h"
#include "./h/area.h"

# define tile_x( num ) = tile % 16;

const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

SDL_Event event;

const char TILE_FILENAME[31] = "Data/df_tileset.bmp";
const int TILE_HEIGHT = 12; //192/16 -- 16,32,48,64,80,    ,160,176,192
const int TILE_WIDTH = 8; // 128/16int main( int argc, char* args[] ) {
const int TILE_NUMBER = 256;
const int TILE_X = 16;
const int TILE_Y = 16;
const int TILE_KEY = 0; // using 256 colors.. black or white
    // 265 colors -- R R R G G G B B for the bits..



void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, int tile_num ) {
     //Holds offsets
     SDL_Rect offset;
     //Get offsets
     offset.x = x;
     offset.y = y;

     // Holds Clip
     SDL_Rect clip;
     clip.x = TILE_WIDTH * (tile_num % 16);
     clip.y = TILE_HEIGHT * (tile_num / 16);
     clip.w = TILE_WIDTH;
     clip.h = TILE_HEIGHT;

     //Blit
     SDL_BlitSurface( source, &clip, destination, &offset );
}



int main( int argc, char* args[] ) {


    // SDL Images
    SDL_Surface* tileset = NULL;
    SDL_Surface* screen = NULL;

    // Start SDL
    SDL_Init( SDL_INIT_EVERYTHING );

    // Setup Screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    // Load Image
    tileset = SDL_LoadBMP( TILE_FILENAME );

    // Create environment to Draw
    //  env Is a matrix of the maximum fitting tile set.
    area* area_test = new area( 40, 10, area::walk );

    for( int i=0; i<area_test->num_ids(); i++ ) {
        int X = i%80 * TILE_WIDTH;
        int Y = i/80 * TILE_HEIGHT;
        apply_surface( X, Y, tileset, screen, area_test->get_tile(i) );
    }

    // Draw Image on the Screen
    // SDL_BlitSurface( tileset, NULL, screen, NULL);

    // Update Screen
    SDL_Flip( screen );

    // Pause
    //SDL_Delay(2000);

    // Event loop
    while( true ) {

        SDL_PollEvent( &event );

        if( event.type == SDL_QUIT ) {
            // Free Loaded tileset
            SDL_FreeSurface( tileset );

            // Quit SDL
            SDL_Quit();

            // Exit loop
            break;
        }
    }

    return 0;
}
